package com.example.understandvideo.controller;

import com.example.understandvideo.pojo.FileResult;
import com.example.understandvideo.pojo.ResultFul;
import com.example.understandvideo.service.CommonService;
import com.example.understandvideo.service.DemoService;
import com.example.understandvideo.tool.FileUtils;
import com.example.understandvideo.tool.Tools;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("api/gateway/demo")
public class DemoController {
    @Autowired
    CommonService service;
    @Autowired
    DemoService demoService;

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public ResultFul uploadFile() {
        demoService.postWord();
        return ResultFul.OK();
    }

    @RequestMapping(value = "/testA", method = RequestMethod.GET)
    public ResultFul testA(@RequestParam(value = "filepath", required = false) String filepath) {
        demoService.postWordA(filepath);
        return ResultFul.OK();
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultFul uploadFile(
            @RequestParam(value = "file", required = false) MultipartFile multipartFile,
            @RequestParam(value = "tag", required = false) String tag,
            @RequestParam(value = "filepath", required = false) String filepath
    ) {
        if (Objects.isNull(multipartFile) && StringUtils.isEmpty(filepath)) {
            return ResultFul.Error();
        }
        if (StringUtils.isEmpty(filepath)) {
            String uuid = Tools.getUUID();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date now = new Date();
            String nowDay = format.format(now);
            File file = new File(service.getWorkSpace() + File.separator + nowDay + File.separator + uuid + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")));
            try {
                // 确保父目录存在
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
                multipartFile.transferTo(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            filepath = file.getAbsolutePath();
        }
        return ResultFul.OK(demoService.videoUnderstand(filepath, tag));
    }

    @GetMapping("/result")
    public ResultFul result(@RequestParam(value = "date", required = false) String date) {
        try {
            if (StringUtils.isEmpty(date)) {
                date = "";
            }
            // 1. 构建文件路径
            Path filePath = Paths.get(service.getWorkSpace() + "result" + File.separator + date);

            // 2. 检查文件是否存在
            if (!Files.exists(filePath) && StringUtils.isEmpty(date)) {
                filePath.toFile().mkdirs();
            }
            List<FileResult> result = new ArrayList<>();
            File[] fileList = filePath.toFile().listFiles();
            if (Objects.nonNull(fileList)) {
                for (File file : fileList) {
                    FileResult fileResult = new FileResult();
                    fileResult.setFilename(file.getName());
                    fileResult.setFilepath(FileUtils.toForwardSlashes(file.getAbsolutePath()));
                    result.add(fileResult);
                }
            }
            return ResultFul.OK(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultFul.Error();
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("path") String path) {
        try {
            // 1. 构建文件路径
            Path filePath = Paths.get(path);

            // 2. 检查文件是否存在
            if (!Files.exists(filePath)) {
                throw new FileNotFoundException("文件不存在: " + path);
            }

            // 3. 创建Resource对象
            Resource resource = new UrlResource(filePath.toUri());

            // 4. 设置HTTP响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);

        } catch (FileNotFoundException e) {
            return ResponseEntity.notFound().build();
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

}
